<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { WorkstationModel } from '#/api/master/models';

import { watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteWorkstationApi,
  getWorkstationPagedListApi,
} from '#/api/master/workstation';
import { $t } from '#/locales';

import { useColumns } from './data-workstation';
import Form from './modules/workstation-form.vue';

defineOptions({
  inheritAttrs: false,
});

const { lineId } = defineProps<{
  lineId?: number;
}>();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 创建新工位
 */
function onCreate() {
  formModalApi.setData(null).open();
}

/**
 * 编辑工位
 */
function onEdit(row: WorkstationModel) {
  formModalApi.setData(row).open();
}

/**
 * 删除工位
 */
function onDelete(row: WorkstationModel) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.wsName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteWorkstationApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.wsName]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<WorkstationModel>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    rowConfig: {
      isHover: true,
      isCurrent: true,
    },
    pagerConfig: {},
    proxyConfig: {
      autoLoad: false,
      ajax: {
        query: async ({ page }) => {
          return await getWorkstationPagedListApi({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            lineId,
          });
        },
      },
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}

watch(
  () => lineId,
  async (value, oldValue) => {
    if (value !== oldValue) {
      await gridApi.reload();
    }
  },
);
</script>

<template>
  <FormModal @success="refreshGrid()" />
  <Grid>
    <template #toolbar-tools>
      <Button type="primary" @click="onCreate()"> 新增工位 </Button>
    </template>
  </Grid>
</template>
